package com.tpln.controller;

import com.tpln.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class AuthController {

    @Autowired
    private AuthService authService;


    @PostMapping("/auth")
    @ResponseBody
    public String auth(String userName, String password, String code, HttpServletRequest req, HttpSession session){
        if(userName == null || password == null || code == null
                || userName.equals("") || password.equals("") || "".equals(code)){
            return "fail";
        }
        // secCode 在 SecCodeController里放入，后期应该放到常量类中
        if (session.getAttribute("secCode").equals(code)) {
            String userId = authService.auth(userName,password);

            if(userId != null && !userId.equals("")){
                session.setAttribute("userId",userId);
                return "ok";
            }
        } else {
            return "codeError";
        }
        return "fail";
    }


    @PostMapping("/selectUserName")
    @ResponseBody
    public String selectUserName(HttpServletRequest req){
        HttpSession session = req.getSession();
        String userId = (String) session.getAttribute("userId");
        if(userId == null || userId.equals("")){
            return "failLogin";
        }
        String userName = authService.findUserNameById(userId);
        if(userName != null && !userName.equals("")){
            return userName;
        }
        return "failLogin";
    }

}
